package com.itheima.controller;

import com.itheima.pojo.Article;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @GetMapping("list")
    public Result<PageBean> list(Integer pageNum, Integer pageSize,
                                 @RequestParam(required = false, defaultValue = "") String title,
                                 @RequestParam(required = false) String categoryId,
                                 @RequestParam(required = false) String state) {

        PageBean<Article> pageBean = articleService.getList(pageNum, pageSize, title, categoryId, state);
        return Result.success(pageBean);
    }

    @PostMapping("add")
    public Result<String> add(@RequestBody @Validated Article article) {
        Integer id = article.getId();
        if (id != null) {
            return articleService.edit(article);
        }
        return articleService.add(article);
    }

    @PostMapping("delete")
    public Result<Boolean> delete(String id) {
        boolean b = articleService.removeById(id);
        return Result.success(b);
    }

}
